package com.xm.logImpl;

import com.xm.common.utils.SecurityUtils;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Aspect
@Component
@Log4j2
public class LogAspectZs {

    @Autowired
    private HttpServletRequest request;

    @Before("execution(* com.xm.*.controller.*.*Controller.*(..))")
    public void after(JoinPoint joinPoint)throws IOException{
        //请求方法
        String url=request.getRequestURI();
        String contentType = request.getContentType(); // 获取请求ContentType
        String parms="";
        if (contentType != null && contentType.startsWith("application/json")) {
            parms=getJson(joinPoint);
        } else {
            parms=getParms();
        }
        String userName="";
        try {
            userName= SecurityUtils.getUsername();
        }catch (Exception e){

        }finally {
            log.info("请求路径:"+url+"----操作用户:"+(userName==null||userName.equals("")?"未登录用户":userName)+"--------请求参数："+parms);
        }

    }

    public String getJson(JoinPoint joinPoint) throws IOException {
        List<Object>ls=new ArrayList<>();
        for (int i = 0; i < joinPoint.getArgs().length; i++) {
            Object object = joinPoint.getArgs()[i];
            ls.add(object);
            if (object instanceof HttpServletRequest || object instanceof HttpServletResponse) {
                continue;
            }

        }
        return ls.toString();
    }



    public String getParms(){
        Map<String, String[]> params = request.getParameterMap(); // 获取请求参数

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            sb.append(key).append("=").append(Arrays.toString(values)).append("]");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        String queryString = sb.toString(); // 获取请求参数的key和value
        return queryString;
    }
}
